﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace ContractManagementSystem.DataAccess
{
    public class ImportDataAccess : SqlProvider
    {
        readonly LogDataAccess _logDataAccess = new LogDataAccess();
        private const string UserName = "Admin";

        public bool Insert(DataTable source)
        {
            if (!string.IsNullOrEmpty(ErrorMessage))
            {
                //log error
                _logDataAccess.WriteError(ErrorMessage, UserName);
                return false;
            }

            try
            {
                //log event                
                _logDataAccess.WriteEvent("Inserting ...", UserName);

                using (var sqlCommand = new SqlCommand())
                {
                    sqlCommand.CommandType = CommandType.StoredProcedure;
                    sqlCommand.UpdatedRowSource = UpdateRowSource.None;
                    sqlCommand.CommandText = "sp_ContractType_InsertList";
                    
                    sqlCommand.Connection = CreateConnection();
                    var sqlDataAdapter = new SqlDataAdapter { InsertCommand = sqlCommand, UpdateBatchSize = source.Rows.Count };
                    sqlDataAdapter.Update(source);
                }
                

            }
            catch (SqlException e)
            {
                ErrorMessage = e.ToString();

                //log event
                _logDataAccess.WriteEvent("Insert fail!", UserName);

                //log error
                _logDataAccess.WriteError(ErrorMessage, UserName);

                return false;

            }
            finally
            {
                CloseConnection();
            }

            //log event
            _logDataAccess.WriteEvent("Insert success!", UserName);

            return true;
        }
    }
}
